package com.demo.utils;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;

public class ScaleFilter {
    private static final Logger logger = LoggerFactory.getLogger(ScaleFilter.class);


    //通过视频生成缩略图
    public static void createCover4Video(File sourceFile,Integer width,File targetFile){
        try {
            String cmd="ffmpeg -i %s -y -vframes 1 -vf scale=%d:%d/a %s";
            CommandUtil.runCmd(String.format(cmd,sourceFile.getPath(),width,width,targetFile.getAbsoluteFile()));
        }catch (Exception e){
            logger.error("生成封面失败",e);
        }
    }


    public static Boolean createThumbnailWidthFFmpeg(File file, int thumbnailWidth,File targetFile,Boolean delSource ){
        try {
            BufferedImage src = ImageIO.read(file);
            //thumbnailWidth 缩略图的宽度   thumbnailHeight 缩略图的高度
            int sorceW = src.getWidth();
            int sorceH = src.getHeight();
            //小于 指定高宽不压缩
            if (sorceW <= thumbnailWidth) {
                return false;
            }
            compressImage(file,thumbnailWidth,targetFile,delSource);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static void compressImage(File sourceFile,Integer width,File targetFile,Boolean delSource){
        try {
//            String cmd="ffmpeg -i %s  -vf scale=%d:-1 %s -y";
            String cmd = "ffmpeg -i %s -vf scale=%d:-1 -q:v 2 %s -y"; // -q:v 2 控制质量（值越小质量越高）
            CommandUtil.runCmd(String.format(cmd,sourceFile.getPath(),width,targetFile.getAbsoluteFile()));
            if (delSource){
                FileUtils.forceDelete(sourceFile);
            }
        }catch (Exception e){
           logger.error("压缩图片失败");
        }
    }

    public static Boolean createThumbnail(File file, int thumbnailWidth, int thumbnailHeight, File targetFile) {
        try {
            BufferedImage src = ImageIO.read(file);
            int sorceW = src.getWidth();
            int sorceH = src.getHeight();
            if (sorceW <= thumbnailWidth) {
                return false;
            }
            int height = thumbnailWidth * sorceH / sorceW;
            BufferedImage dst = new BufferedImage(thumbnailWidth, height, BufferedImage.TYPE_INT_RGB);
            Image scaleImage = src.getScaledInstance(thumbnailWidth, height, Image.SCALE_SMOOTH);
            Graphics2D g = dst.createGraphics();
            g.drawImage(scaleImage, 0, 0, thumbnailWidth, height, null);
            g.dispose();
            if (height > thumbnailHeight) {
                dst = dst.getSubimage(0, 0, thumbnailWidth, thumbnailHeight);
            }

            // 设置压缩质量
            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
            ImageWriter writer = writers.next();
            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(1f); // 设置压缩质量（0.0 到 1.0）

            try (ImageOutputStream out = ImageIO.createImageOutputStream(targetFile)) {
                writer.setOutput(out);
                writer.write(null, new IIOImage(dst, null, null), param);
            }
            writer.dispose();
            return true;
        } catch (Exception e) {
            logger.error("生成缩略图失败", e);
        }
        return false;
    }


    public static void main(String[] args) {
        createThumbnail(new File("C:\\Users\\Administrator\\Pictures\\20180316193912_VJWJG11.jpeg"), 400, 200,
                new File("C:\\Users\\Administrator\\Pictures\\20180316193912_VJWJG12.jpeg"));
    }
}